package study.web.security;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import study.domain.Constants;
import study.domain.user.User;

/**
 * Spring Security의 RememberMe를 통해서 인증된 경우 세션에 사용자 정보를 넣어준다.
 *
 * @author Barney
 */
public class UserRememberMeFilter extends GenericFilterBean {

	@Resource(name = "securitySupport")
	private SecuritySupport securitySupport;

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth != null && auth instanceof RememberMeAuthenticationToken) {
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute(Constants.SESSION_KEY);
			if (user == null) {
				String username = securitySupport.getUsername(auth);
				securitySupport.setSessionUser(request, username);
			}
		}
		chain.doFilter(req, res);
	}
}
